package com.shop.cloud.auth.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.constant.SecurityConstants;
import com.shop.cloud.common.core.util.IpUtils;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.data.tenant.TenantContextHolder;
import com.shop.cloud.upms.common.entity.SysLogLogin;
import com.shop.cloud.upms.common.feign.FeignLogLoginService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * @author 辰
 * @date 2023年10月26日18:19:19
 */
@Slf4j
@AllArgsConstructor
public class BaseAuthenticationFailureEventHandler implements AuthenticationFailureHandler {

	private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter();
	private final FeignLogLoginService feignLogLoginService;

	/**
	 * Called when an authentication attempt fails.
	 * @param request the request during which the authentication attempt occurred.
	 * @param response the response.
	 * @param exception the exception which was thrown to reject the authentication
	 * request.
	 */
	@Override
	@SneakyThrows
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
										AuthenticationException exception) {
		String username = request.getParameter(OAuth2ParameterNames.USERNAME);
		String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
		OAuth2AuthenticationException exceptionOAuth2 = (OAuth2AuthenticationException)exception;
//		log.info("用户：{} 登录失败，异常：{}", username, exception.getLocalizedMessage());
		CompletableFuture.runAsync(() -> {
			TenantContextHolder.setTenantId(CommonConstants.SYSTEM_TENANT_ID);
			SysLogLogin sysLogLogin = new SysLogLogin();
			sysLogLogin.setType(CommonConstants.LOG_TYPE_9);
			sysLogLogin.setGrantType(grantType);
			sysLogLogin.setCreateBy(username);
			sysLogLogin.setRemoteAddr(request.getRemoteAddr());
			sysLogLogin.setRequestUri(URLUtil.getPath(request.getRequestURI()));
			sysLogLogin.setUserAgent(request.getHeader("user-agent"));
//			sysLogLogin.setParams(HttpUtil.toParams(request.getParameterMap()));
			sysLogLogin.setException(exceptionOAuth2.getError().getErrorCode());
			String address = IpUtils.getAddresses(sysLogLogin.getRemoteAddr());
			sysLogLogin.setAddress(address);
			feignLogLoginService.saveLogLogin(sysLogLogin, SecurityConstants.FROM_IN);
		});
		// 写出错误信息
		sendErrorResponse(request, response, exception);
	}

	private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
								   AuthenticationException exception) throws IOException {
		ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
		httpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
		String errorMessage;

		if (exception instanceof OAuth2AuthenticationException) {
			OAuth2AuthenticationException authorizationException = (OAuth2AuthenticationException) exception;
			errorMessage = StrUtil.isBlank(authorizationException.getError().getDescription())
					? authorizationException.getError().getErrorCode()
					: authorizationException.getError().getDescription();
		}
		else {
			errorMessage = exception.getLocalizedMessage();
		}

		this.errorHttpResponseConverter.write(R.failed(errorMessage), MediaType.APPLICATION_JSON, httpResponse);
	}
}
